"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setStateValue = exports.getStateValue = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const lang_1 = require("../utils/lang");
const config_1 = require("../constants/config");
const logger_1 = require("../lib/logger");
const config_2 = require("../constants/config");
const i18nKey = 'config.state';
const DEFAULT_STATE = {
    [config_2.MCP_TOTAL_TOOL_CALLS_STATE]: 0,
};
function ensureCLIDirectory() {
    try {
        const dir = path.dirname(config_1.STATE_FILE_PATH);
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
        }
    }
    catch (error) {
        throw new Error((0, lang_1.i18n)(`${i18nKey}.ensureCLIDirectory.errors.cannotCreateDirectory`, {
            error: error instanceof Error ? error.message : String(error),
        }));
    }
}
function sanitizeAndMerge(parsed) {
    if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
        return structuredClone(DEFAULT_STATE);
    }
    const state = parsed;
    const result = structuredClone(DEFAULT_STATE);
    for (const key in DEFAULT_STATE) {
        const typedKey = key;
        if (key in state &&
            typeof state[typedKey] === typeof DEFAULT_STATE[typedKey]) {
            result[typedKey] = state[typedKey];
        }
        // keys not in parsed file remain as DEFAULT values
    }
    return result;
}
function getCurrentState() {
    try {
        if (!fs.existsSync(config_1.STATE_FILE_PATH)) {
            return structuredClone(DEFAULT_STATE);
        }
        const data = fs.readFileSync(config_1.STATE_FILE_PATH, 'utf-8');
        if (!data?.trim()) {
            logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.getCurrentState.debug.emptyStateFile`));
            return structuredClone(DEFAULT_STATE);
        }
        const parsed = JSON.parse(data);
        return sanitizeAndMerge(parsed);
    }
    catch (error) {
        logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.getCurrentState.errors.errorReading`, {
            error: error instanceof Error ? error.message : String(error),
        }));
        return structuredClone(DEFAULT_STATE);
    }
}
function getStateValue(key) {
    ensureCLIDirectory();
    const state = getCurrentState();
    return state[key];
}
exports.getStateValue = getStateValue;
function setStateValue(key, value) {
    ensureCLIDirectory();
    const currentState = getCurrentState();
    const newState = { ...currentState, [key]: value };
    try {
        fs.writeFileSync(config_1.STATE_FILE_PATH, JSON.stringify(newState, null, 2), 'utf-8');
    }
    catch (error) {
        throw new Error((0, lang_1.i18n)(`${i18nKey}.setStateValue.errors.failedToWrite`, {
            error: error instanceof Error ? error.message : String(error),
        }));
    }
}
exports.setStateValue = setStateValue;
